package net.zjitc.dao.impl;

import net.zjitc.dao.ProductDao;
import net.zjitc.domain.Product;
import net.zjitc.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @Author admin
 * @Date 2019/2/25 9:21
 */
public class ProductDaoImpl implements ProductDao {
    @Override
    public List<Product> findAll() throws SQLException {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from product";
        List<Product>list = runner.query(sql,new BeanListHandler<Product>(Product.class));
        return list;
    }

    @Override
    public void add(Product product) throws SQLException {
        String sql = "insert into product(pname,marketprice,shopprice,pdesc,ishot,image) value(?,?,?,?,?,?)";
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        runner.update(sql,new Object[]{product.getPname(),product.getMarketprice(),product.getShopprice(),product.getPdesc(),product.getIshot(),product.getImage()});

    }

    @Override
    public Product fingById(String pid) throws SQLException {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "SELECT * FROM product WHERE pid = ?;";
        Product product = (Product) runner.query(sql,new BeanHandler(Product.class),pid);
        return product;
    }

    @Override
    public void update(Product product, String pid) throws SQLException {
        QueryRunner runner = new QueryRunner((C3P0Utils.getDataSource()));
        String sql = "update product set pname=?,marketprice=?,shopprice=?,pdesc=?,ishot=? where pid=?";
        runner.update(sql,new Object[]{product.getPname(),product.getMarketprice(),product.getShopprice(),product.getPdesc(),product.getIshot(),pid});

    }

    @Override
    public void delete(String pid) throws SQLException {
        String sql = "delete from product where pid = ?";
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        runner.update(sql,pid);

    }



}
